package com.springcloud;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

/**
 * @author 顾志杰
 * @date 2021/5/31-10:49
 */
@Service
@Slf4j
@Deprecated
public class AccessLimiter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisScript<Boolean> rateLimitLua;

    /**
     * 限流方法
     * @param key  方法的特征
     * @param limit 一秒钟之内通过多少个请求
     */
    public void limiterAccess(String key,Integer limit){
        /*step 1 : request Lua script*/
        boolean acquired = redisTemplate.execute(
                rateLimitLua, // Lua 脚本
                Lists.newArrayList(key), // Lua脚本中的key列表
                limit.toString() //Lua脚本中的value列表
        );
        if(!acquired){
            log.error("Your access is blocked, key = {}",key);
            throw new RuntimeException("请求不通过");
        }
    }



}
